# -*- coding: utf-8 -*-
import time
from celery import Celery
from setting import CELERY_BROKER_URL,REDIS_DB_URL,PG_DATABASE_INFO,TOKEN_CACHE_KEY,WEAPP_ID,WEAPP_SECRET
import redis
import psycopg2
from datetime import datetime
import simplejson as json
import requests

api_celery = Celery('QR_api_celery', broker=CELERY_BROKER_URL)
CELERY_CREATE_MISSING_QUEUES = True  # 某个程序中出现的队列，在broker中不存在，则立刻创建它
CELERYD_FORCE_EXECV = True    # 非常重要,有些情况下可以防止死锁
# 任务发出后，经过一段时间还未收到acknowledge , 就将任务重新交给其他worker执行
CELERY_DISABLE_RATE_LIMITS = True



def set_cache(key_name, re_info, cache_time):
    conn = redis.Redis(**REDIS_DB_URL)
    try:
        conn.set(key_name, re_info)
        conn.expire(key_name, cache_time)
        return True
    except redis.ConnectionError, redis.ResponseError:
        return False


def get_access_token():
    access_token_url = "https://api.weixin.qq.com/cgi-bin/token"
    payload = {
        'grant_type':'client_credential',#获取 access_token 填写 client_credential
        'appid': WEAPP_ID,
        'secret': WEAPP_SECRET
    }
    json_info = requests.get (access_token_url, params=payload, verify=False).json ()
    print '************'
    print json_info
    if not json_info.get ('expires_in'): #
        errcode = json_info['errcode']
        #tornado.ioloop.IOLoop.instance ().call_later (10,get_access_token)
    else:
        access_token = json_info.get ('access_token')
        expires_in_seconds = int (json_info.get ('expires_in') * 0.9)
        set_cache (TOKEN_CACHE_KEY, access_token, expires_in_seconds)
        return access_token


def get_cache(key_name):
    coon = redis.Redis(**REDIS_DB_URL)
    try:
        if not coon.exists (key_name):
            access_token=get_access_token()
            return access_token
        re_value = coon.get(key_name)
        if re_value:
            return re_value
        else:
            return dict(errcode=1)

    except redis.ConnectionError, redis.ResponseError:
        print redis.ConnectionError, redis.ResponseError
        return dict(errcode=-1)


@api_celery.task()
def api_log_sys(method_name, re_data, args,api_key):
    log_list_name = 'API_QRCODE_LOGS_CACHE'
    conn = redis.Redis(**REDIS_DB_URL)
    print '111111111'
    log_content = {
        'method_name': method_name,
        'args':json.dumps(args),
        're_data': json.dumps(re_data),
        'api_key': api_key,
        'time': str(datetime.now()),
    }

    conn.rpush(log_list_name, str(log_content))
    count_cache_los = conn.llen(log_list_name)
    if count_cache_los >= 100:
        conn_db = psycopg2.connect(**PG_DATABASE_INFO)
        cursor = conn_db.cursor()
        while True:
            each_cache_log = conn.lpop(log_list_name)
            if each_cache_log:
                each_log_info = eval(each_cache_log)
                cursor.execute("INSERT INTO api_log (method_name, re_data, api_key, args, time) "
                               "VALUES (%(method_name)s, %(re_data)s, %(api_key)s, %(args)s, "
                               "to_timestamp(%(time)s, 'YYYY-MM-DD HH24:MI:SS.US'))",
                               {
                                   'method_name': each_log_info['method_name'],
                                   're_data': each_log_info['re_data'],
                                   'api_key': each_log_info['api_key'] if each_log_info['api_key'] else 'None',
                                   'args': each_log_info['args'],
                                   'time': each_log_info['time'],
                               }
                               )
            else:
                break
        conn_db.commit()
        conn_db.close()

def get_post_url():
    print get_cache(TOKEN_CACHE_KEY)
    return 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + get_cache(TOKEN_CACHE_KEY)

def  send_notify_template_by_openid(openid):
    template_id = {
        1: 'I_2tN4acDumE5r3dcnwgBqxUM0RJtUIvpYyRzg', #模板消息的ID
        2: 'sa04EHs5xqKpdi8rDij9wIkyJjzXL-HFRkAqOnW5duw',
    }
    notify_template={
        "touser": openid,
        "template_id": u"zlm_H_bY7cG3CZmqByPj4BB6tQMHxVMgW-KijODk-Vk",
        # "page": "",
        # "form_id": "",
        "data": {
            "keyword1": {
                "value": "339208499"
            },
            "keyword2": {
                "value": "2015年01月05日 12:30"
            },
            "keyword3": {
                "value": "粤海喜来登酒店"
            },
            "keyword4": {
                "value": "广州市天河区天河路208号"
            },
            "keyword5": {
                "value": "广州市天河区天河路208号"
            }
        },
    }
    print json.dumps(notify_template)
    json_info=requests.post(get_post_url(), data=json.dumps(notify_template),verify=False)
    print '$$$$$$$$$$$$'
    print json_info.json()